package com.mibus.mibusmobile;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;

import java.io.IOException;

public class RequestGet extends AsyncTask<String,Integer,String> {
    private Context context;

    public RequestGet(Context context){
        this.context = context;
    }
    protected String doInBackground(String... url){
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
        HttpConnectionParams.setSoTimeout(httpParameters, 10000);

        HttpClient httpclient = new DefaultHttpClient(httpParameters);
        HttpGet httpget= new HttpGet(url[0]);
        String result = "NoInternet";
        if(checkOnlineState()){
            try {
                HttpResponse response = httpclient.execute(httpget);
                HttpEntity entity = response.getEntity();
                result = JSONParser.inputStreamToString(entity.getContent()).toString();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }else{
            return "NoInternet";
        }
    }

    public boolean checkOnlineState() {
        ConnectivityManager CManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo NInfo = CManager.getActiveNetworkInfo();
        if (NInfo != null && NInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }
}
